<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\Purchase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PurchaseController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $data=Purchase::with(['product'=>function($query){
            $query->select('name','id');
        },'admin'=>function($query){
            $query->select('id','username');
        }])->paginate(10);
//        dd(Purchase::with('product'))->get();
        $products=DB::table('products')->select('id','name')->get();

        return $this->success(compact('data','products'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->merge(['admin'=>$request->adminId]);
        $request->merge(['created_at'=>time()]);
        if( DB::table('purchase')->insert($request->all())) return $this->success();
        return $this->apiError();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if( DB::table('purchase')->whereId($id)->update($request->all())) return $this->success();
        return $this->apiError();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if( DB::table('purchase')->delete($id)) return $this->success();
        return $this->apiError();
    }
}
